#include "../include/loginwidget.h"
#include "../include/config.h"
#include <QMessageBox>
#include <QApplication>
#include <QPixmap>
#include <QFont>

LoginWidget::LoginWidget(AuthService *authService, QWidget *parent)
    : QWidget(parent)
    , m_authService(authService)
    , m_primaryColor("#4A90E2")
    , m_secondaryColor("#7ED321")
    , m_backgroundColor("#2C3E50")
    , m_textColor("#ECF0F1")
    , m_errorColor("#E74C3C")
    , m_successColor("#27AE60")
{
    setupUI();
    applyStyles();

    connect(m_authService, &AuthService::loginSucceeded,
            this, &LoginWidget::onLoginSucceeded);
    connect(m_authService, &AuthService::loginFailed,
            this, &LoginWidget::onLoginFailed);
}

LoginWidget::~LoginWidget()
{
    // 所有UI组件通过Qt的父子关系自动管理
}

void LoginWidget::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setSpacing(0);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);

    // 确保窗口填满整个区域
    this->setContentsMargins(0, 0, 0, 0);

    // 创建主容器 - 使用居中卡片设计
    QWidget *mainContainer = new QWidget();
    mainContainer->setObjectName("loginMainContainer");

    QHBoxLayout *containerLayout = new QHBoxLayout(mainContainer);
    containerLayout->setContentsMargins(0, 0, 0, 0);
    containerLayout->setSpacing(0);

    // 左侧空白区域 (10%)
    QWidget *leftSpacer = new QWidget();
    leftSpacer->setObjectName("spacerWidget");

    // 中央登录卡片 (80%)
    QWidget *centerCard = new QWidget();
    centerCard->setObjectName("loginCard");
    centerCard->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 右侧空白区域 (10%)
    QWidget *rightSpacer = new QWidget();
    rightSpacer->setObjectName("spacerWidget");

    // 设置比例：左10% 中80% 右10%
    containerLayout->addWidget(leftSpacer, 1);
    containerLayout->addWidget(centerCard, 8);
    containerLayout->addWidget(rightSpacer, 1);

    // 设置登录卡片内容
    setupLoginCard(centerCard);

    m_mainLayout->addWidget(mainContainer);
}

void LoginWidget::setupLoginCard(QWidget *centerCard)
{
    QVBoxLayout *cardLayout = new QVBoxLayout(centerCard);
    cardLayout->setContentsMargins(0, 0, 0, 0);
    cardLayout->setSpacing(0);

    // 创建登录表单容器 (垂直居中)
    QWidget *formContainer = new QWidget();
    formContainer->setObjectName("loginFormContainer");
    formContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    QVBoxLayout *formLayout = new QVBoxLayout(formContainer);
    formLayout->setContentsMargins(40, 10, 40, 30); // 进一步减少顶部边距
    formLayout->setSpacing(20);

    // 重新设计的头部区域 - 左图标 + 中间文字 + 右装饰
    QWidget *headerWidget = new QWidget();
    QHBoxLayout *headerLayout = new QHBoxLayout(headerWidget);
    headerLayout->setSpacing(20);
    headerLayout->setContentsMargins(0, 0, 0, 0);

    // 左侧Logo图标
    m_logoLabel = new QLabel();
    m_logoLabel->setText("🎮");
    m_logoLabel->setAlignment(Qt::AlignCenter);
    m_logoLabel->setObjectName("loginLogo");
    m_logoLabel->setFixedSize(50, 50);
    headerLayout->addWidget(m_logoLabel);

    // 中间标题区域 - 居中对齐
    QWidget *titleWidget = new QWidget();
    QVBoxLayout *titleLayout = new QVBoxLayout(titleWidget);
    titleLayout->setSpacing(5);
    titleLayout->setContentsMargins(0, 0, 0, 0);

    m_titleLabel = new QLabel("欢迎回来");
    m_titleLabel->setAlignment(Qt::AlignCenter);
    m_titleLabel->setObjectName("loginTitle");
    titleLayout->addWidget(m_titleLabel);

    QLabel *subtitle = new QLabel("请登录您的账户继续游戏");
    subtitle->setAlignment(Qt::AlignCenter);
    subtitle->setObjectName("loginSubtitle");
    titleLayout->addWidget(subtitle);

    headerLayout->addWidget(titleWidget, 1); // 给标题区域更多空间

    // 右侧装饰图标
    QLabel *decorIcon = new QLabel();
    decorIcon->setText("🚀");
    decorIcon->setAlignment(Qt::AlignCenter);
    decorIcon->setObjectName("decorIcon");
    decorIcon->setFixedSize(50, 50);
    headerLayout->addWidget(decorIcon);

    formLayout->addWidget(headerWidget);

    // 表单区域 - 增加更多空间给输入框
    QWidget *inputsWidget = new QWidget();
    QVBoxLayout *inputsLayout = new QVBoxLayout(inputsWidget);
    inputsLayout->setSpacing(15);

    // 用户名输入组件
    QWidget *usernameGroup = createInputGroup("👤", "用户名", "请输入用户名或邮箱", m_usernameEdit);
    inputsLayout->addWidget(usernameGroup);

    // 密码输入组件
    QWidget *passwordGroup = createInputGroup("🔒", "密码", "请输入密码", m_passwordEdit);
    m_passwordEdit->setEchoMode(QLineEdit::Password);
    inputsLayout->addWidget(passwordGroup);

    formLayout->addWidget(inputsWidget);

    // 选项区域
    QWidget *optionsWidget = new QWidget();
    QHBoxLayout *optionsLayout = new QHBoxLayout(optionsWidget);
    optionsLayout->setContentsMargins(5, 0, 5, 0);
    optionsLayout->setSpacing(0);

    m_rememberCheck = new QCheckBox("记住我");
    m_rememberCheck->setObjectName("modernCheckbox");
    optionsLayout->addWidget(m_rememberCheck);

    optionsLayout->addStretch();

    m_forgotPasswordButton = new QPushButton("忘记密码?");
    m_forgotPasswordButton->setObjectName("linkButton");
    connect(m_forgotPasswordButton, &QPushButton::clicked, this, &LoginWidget::onForgotPasswordClicked);
    optionsLayout->addWidget(m_forgotPasswordButton);

    formLayout->addWidget(optionsWidget);

    // 登录按钮
    m_loginButton = new QPushButton("🚀 立即登录");
    m_loginButton->setObjectName("modernPrimaryButton");
    m_loginButton->setDefault(true);
    m_loginButton->setMinimumHeight(48); // 增加按钮高度
    connect(m_loginButton, &QPushButton::clicked, this, &LoginWidget::onLoginClicked);
    formLayout->addWidget(m_loginButton);

    // 分隔线
    QFrame *separator = new QFrame();
    separator->setObjectName("separator");
    separator->setFrameShape(QFrame::HLine);
    separator->setFrameShadow(QFrame::Sunken);
    formLayout->addWidget(separator);

    // 注册链接
    QHBoxLayout *registerLayout = new QHBoxLayout();
    QLabel *noAccountLabel = new QLabel("还没有账户?");
    noAccountLabel->setObjectName("hintLabel");

    m_registerButton = new QPushButton("立即注册");
    m_registerButton->setObjectName("secondaryButton");
    connect(m_registerButton, &QPushButton::clicked, this, &LoginWidget::onRegisterClicked);

    registerLayout->addStretch();
    registerLayout->addWidget(noAccountLabel);
    registerLayout->addWidget(m_registerButton);
    registerLayout->addStretch();
    formLayout->addLayout(registerLayout);

    // 状态显示
    m_statusLabel = new QLabel();
    m_statusLabel->setObjectName("statusLabel");
    m_statusLabel->setAlignment(Qt::AlignCenter);
    m_statusLabel->setWordWrap(true);
    formLayout->addWidget(m_statusLabel);

    m_progressBar = new QProgressBar();
    m_progressBar->setObjectName("modernProgressBar");
    m_progressBar->setVisible(false);
    formLayout->addWidget(m_progressBar);

    // 将表单容器垂直居中，减少上方空白
    cardLayout->addStretch(1);
    cardLayout->addWidget(formContainer);
    cardLayout->addStretch(2);

    // 连接信号
    connect(m_passwordEdit, &QLineEdit::returnPressed, this, &LoginWidget::onLoginClicked);
    connect(m_usernameEdit, &QLineEdit::returnPressed, this, &LoginWidget::onLoginClicked);

    // 设置焦点
    m_usernameEdit->setFocus();
}

QWidget* LoginWidget::createInputGroup(const QString &icon, const QString &label, const QString &placeholder, QLineEdit *&lineEdit)
{
    QWidget *group = new QWidget();
    group->setObjectName("inputGroup");

    QVBoxLayout *groupLayout = new QVBoxLayout(group);
    groupLayout->setContentsMargins(0, 0, 0, 0);
    groupLayout->setSpacing(8);

    // 标签容器
    QWidget *labelContainer = new QWidget();
    QHBoxLayout *labelLayout = new QHBoxLayout(labelContainer);
    labelLayout->setContentsMargins(0, 0, 0, 0);
    labelLayout->setSpacing(8);

    // 图标标签 - 缩小尺寸
    QLabel *iconLabel = new QLabel(icon);
    iconLabel->setObjectName("inputIcon");
    iconLabel->setFixedSize(16, 16);
    iconLabel->setAlignment(Qt::AlignCenter);

    // 文字标签
    QLabel *textLabel = new QLabel(label);
    textLabel->setObjectName("inputLabel");

    labelLayout->addWidget(iconLabel);
    labelLayout->addWidget(textLabel);
    labelLayout->addStretch();

    // 输入框容器 - 增加最小高度
    QWidget *inputContainer = new QWidget();
    inputContainer->setObjectName("inputContainer");
    inputContainer->setMinimumHeight(45); // 设置最小高度
    QHBoxLayout *inputLayout = new QHBoxLayout(inputContainer);
    inputLayout->setContentsMargins(15, 12, 15, 12);
    inputLayout->setSpacing(0);

    // 创建输入框 - 设置最小尺寸
    lineEdit = new QLineEdit();
    lineEdit->setObjectName("modernInput");
    lineEdit->setPlaceholderText(placeholder);
    lineEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
    lineEdit->setMinimumHeight(21); // 设置最小高度
    lineEdit->setMinimumWidth(200); // 设置最小宽度

    inputLayout->addWidget(lineEdit);

    groupLayout->addWidget(labelContainer);
    groupLayout->addWidget(inputContainer);

    return group;
}

void LoginWidget::applyStyles()
{
    setStyleSheet(QString(R"(
        QWidget {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 %1, stop:0.5 #34495E, stop:1 #2C3E50);
            color: %2;
            font-family: 'Microsoft YaHei', 'Segoe UI', Arial, sans-serif;
        }

        #spacerWidget {
            background: transparent;
        }

        #loginMainContainer {
            background: transparent;
        }

        #loginCard {
            background: transparent;
        }

        #loginFormContainer {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(44, 62, 80, 0.95), stop:1 rgba(52, 73, 94, 0.95));
            border-radius: 25px;
            /* 移除不支持的box-shadow属性 */
            border: 2px solid rgba(74, 144, 226, 0.6);
        }

        #loginFormContainer:hover {
            /* 移除不支持的box-shadow属性 */
            border-color: rgba(74, 144, 226, 0.8);
        }

        #loginLogo {
            font-size: 40px;
            color: %3;
            /* 移除不支持的text-shadow属性 */
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 rgba(74, 144, 226, 0.2), stop:1 rgba(52, 152, 219, 0.2));
            border-radius: 25px;
            border: 2px solid rgba(74, 144, 226, 0.4);
        }

        #decorIcon {
            font-size: 35px;
            color: #F39C12;
            /* 移除不支持的text-shadow属性 */
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 rgba(243, 156, 18, 0.2), stop:1 rgba(230, 126, 34, 0.2));
            border-radius: 25px;
            border: 2px solid rgba(243, 156, 18, 0.4);
        }

        #decorIcon:hover {
            /* 移除不支持的transform和text-shadow属性 */
            border-color: rgba(243, 156, 18, 0.6);
        }

        #loginTitle {
            color: %2;
            font-size: 26px;
            font-weight: bold;
            margin-bottom: 5px;
            /* 移除不支持的text-shadow属性 */
        }

        #loginSubtitle {
            color: #BDC3C7;
            font-size: 15px;
            font-weight: 400;
            margin-bottom: 15px;
        }

        #loginTitle {
            color: #2C3E50;
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        #loginSubtitle {
            color: #7F8C8D;
            font-size: 16px;
            font-weight: 400;
            margin-bottom: 20px;
        }

        /* 输入组件样式 */
        #inputGroup {
            margin-bottom: 5px;
        }

        #inputIcon {
            color: %3;
            font-size: 14px;
            font-weight: bold;
        }

        #inputLabel {
            color: %2;
            font-size: 13px;
            font-weight: 600;
            /* 移除不支持的text-shadow属性 */
        }

        #inputContainer {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(52, 73, 94, 0.8), stop:1 rgba(44, 62, 80, 0.8));
            border: 2px solid rgba(74, 144, 226, 0.4);
            border-radius: 12px;
            margin-top: 5px;
            min-height: 45px;
        }

        #inputContainer:hover {
            border-color: rgba(74, 144, 226, 0.8);
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(58, 83, 104, 0.9), stop:1 rgba(52, 73, 94, 0.9));
            /* 移除不支持的transform属性 */
        }

        #inputContainer:focus-within {
            border-color: %3;
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(58, 83, 104, 0.95), stop:1 rgba(52, 73, 94, 0.95));
            /* 移除不支持的box-shadow和transform属性 */
        }

        #modernInput {
            background: transparent;
            border: none;
            font-size: 16px;
            color: %2;
            min-height: 20px;
        }

        #modernInput:focus {
            outline: none;
        }

        #modernInput::placeholder {
            color: #95A5A6;
            font-style: italic;
        }

        #passwordToggleBtn {
            background: transparent;
            border: none;
            color: #95A5A6;
            font-size: 16px;
            padding: 5px;
            border-radius: 6px;
            min-width: 30px;
            max-width: 30px;
        }

        #passwordToggleBtn:hover {
            background: rgba(74, 144, 226, 0.2);
            color: %3;
        }

        #passwordToggleBtn:checked {
            color: %3;
            background: rgba(74, 144, 226, 0.3);
        }

        #modernCheckbox {
            color: %2;
            font-size: 14px;
            spacing: 8px;
        }

        #modernCheckbox::indicator {
            width: 18px;
            height: 18px;
            border-radius: 4px;
            border: 2px solid rgba(74, 144, 226, 0.6);
            background: rgba(44, 62, 80, 0.8);
        }

        #modernCheckbox::indicator:checked {
            background: %3;
            border-color: %3;
            image: url();
        }

        #modernPrimaryButton {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 %3, stop:1 #3498DB);
            color: white;
            border: none;
            border-radius: 12px;
            padding: 15px 30px;
            font-size: 16px;
            font-weight: bold;
            min-height: 48px;
        }

        #modernPrimaryButton:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #5DADE2, stop:1 #4A90E2);
            /* 移除不支持的box-shadow和transform属性 */
        }

        #modernPrimaryButton:pressed {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #3498DB, stop:1 #2980B9);
        }

        #linkButton {
            background: transparent;
            color: %3;
            border: none;
            font-size: 14px;
            font-weight: 500;
            text-decoration: underline;
        }

        #linkButton:hover {
            color: #5DADE2;
            /* 移除不支持的text-shadow属性 */
        }

        #secondaryButton {
            background: transparent;
            color: %3;
            border: 2px solid rgba(74, 144, 226, 0.6);
            border-radius: 8px;
            padding: 8px 16px;
            font-size: 14px;
            font-weight: 600;
        }

        #secondaryButton:hover {
            background: rgba(74, 144, 226, 0.8);
            color: white;
            border-color: %3;
        }

        #separator {
            background: rgba(74, 144, 226, 0.3);
            margin: 20px 0;
        }

        #hintLabel {
            color: #BDC3C7;
            font-size: 14px;
        }

        #modernProgressBar {
            border: none;
            border-radius: 6px;
            background: #E9ECEF;
            height: 8px;
        }

        #modernProgressBar::chunk {
            background: %3;
            border-radius: 6px;
        }
    )").arg(m_backgroundColor, m_textColor, m_primaryColor));

}

void LoginWidget::onLoginClicked()
{
    QString username = m_usernameEdit->text().trimmed();
    QString password = m_passwordEdit->text();

    if (username.isEmpty()) {
        m_statusLabel->setText("请输入用户名");
        m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_usernameEdit->setFocus();
        return;
    }

    if (password.isEmpty()) {
        m_statusLabel->setText("请输入密码");
        m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_passwordEdit->setFocus();
        return;
    }

    setUIEnabled(false);
    m_progressBar->setVisible(true);
    m_statusLabel->setText("正在登录...");
    m_statusLabel->setStyleSheet("color: #3498DB; background-color: rgba(52, 152, 219, 0.1);");

    m_authService->login(username, password, m_rememberCheck->isChecked());
}

void LoginWidget::onRegisterClicked()
{
    emit switchToRegister();
}

void LoginWidget::onForgotPasswordClicked()
{
    emit switchToForgotPassword();
}

void LoginWidget::onLoginSucceeded(const AuthService::UserInfo &userInfo)
{
    setUIEnabled(true);
    m_progressBar->setVisible(false);
    m_statusLabel->setText(QString("欢迎回来, %1!").arg(userInfo.username));
    m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(39, 174, 96, 0.1);").arg(m_successColor));
    
    clearForm();
    emit loginSucceeded();
}

void LoginWidget::onLoginFailed(const QString &error)
{
    setUIEnabled(true);
    m_progressBar->setVisible(false);
    m_statusLabel->setText(error);
    m_statusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
    
    // 清空密码字段
    m_passwordEdit->clear();
    m_passwordEdit->setFocus();
}



void LoginWidget::setUIEnabled(bool enabled)
{
    m_usernameEdit->setEnabled(enabled);
    m_passwordEdit->setEnabled(enabled);
    m_rememberCheck->setEnabled(enabled);
    m_loginButton->setEnabled(enabled);
    m_registerButton->setEnabled(enabled);
    m_forgotPasswordButton->setEnabled(enabled);
}

void LoginWidget::clearForm()
{
    m_usernameEdit->clear();
    m_passwordEdit->clear();
    m_rememberCheck->setChecked(false);
    m_statusLabel->clear();
}
